package cn.tworice.common.utils;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 保存键值和时效到redis
     * @author 二饭
     * @email 1786705138@qq.com
     */
    public void save(String key,String val,Long ms){
        redisTemplate.opsForValue().set(key,val,ms,TimeUnit.MILLISECONDS);
    }

    // 判断redis中是否存在key和val
    public Boolean exist(String key,String val){
        String mail;
        try{
            mail =(String) redisTemplate.opsForValue().get(key);
        }catch (Exception ex){
            return false;
        }

        if(mail==null || mail.equals("null")){
            return false;
        }
        if(mail.equals(val)){
            return true;
        }
        return false;
    }

    /**
     * 通过key值获取val值
     * @author 二饭
     * @email 1786705138@qq.com
     */
    public Object getValByKey(String key){
        Object val =redisTemplate.opsForValue().get(key);
        return val;
    }
}
